package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.PurchaseInBuilder;
import com.ray.business.builder.PurchaseInRecordBuilder;
import com.ray.business.builder.PurchaseGoodsBuilder;
import com.ray.business.builder.PurchaseInRecordVoBuilder;
import com.ray.business.check.PurchaseInCheck;
import com.ray.business.check.PurchaseCheck;
import com.ray.business.enums.PurchaseInStatusEnum;
import com.ray.business.enums.SaleStatusEnum;
import com.ray.business.service.ProdPurchaseInRecordService;
import com.ray.business.service.ProdPurchaseInService;
import com.ray.business.service.ProdPurchaseRecordService;
import com.ray.business.service.ProdPurchaseService;
import com.ray.business.table.dto.PurchaseInQueryDTO;
import com.ray.business.table.dto.PurchaseInRecordQueryDTO;
import com.ray.business.table.dto.UpdateQuantityDTO;
import com.ray.business.table.entity.ProdPurchase;
import com.ray.business.table.entity.ProdPurchaseIn;
import com.ray.business.table.entity.ProdPurchaseInRecord;
import com.ray.business.table.entity.ProdPurchaseRecord;
import com.ray.business.table.params.purchase.in.PurchaseInCreateParams;
import com.ray.business.table.params.purchase.in.PurchaseInEditParams;
import com.ray.business.table.params.purchase.in.PurchaseInQueryParams;
import com.ray.business.table.params.purchase.in.PurchaseInRecordQueryParams;
import com.ray.business.table.vo.PurchaseInRecordVO;
import com.ray.business.table.vo.PurchaseInVO;
import com.ray.business.table.vo.PurchaseGoodsVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.system.enums.FileTypeEnum;
import com.ray.system.service.SysFileService;
import com.ray.system.table.entity.SysFile;
import com.ray.util.FileRecordUtil;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.builder.GoodsBuilder;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.service.compose.InService;
import com.ray.wms.service.compose.OutService;
import com.ray.wms.table.dto.GoodsDTO;
import com.ray.wms.table.dto.OrderCreateDTO;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.config.SysFileConfig;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description:
 * @Class: PurchaseInBackApi
 * @Package com.ray.business.api
 * @date 2020/6/8 13:39
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class PurchaseInApi {

    @Autowired
    private ProdPurchaseInService prodPurchaseInService;
    @Autowired
    private ProdPurchaseInRecordService prodPurchaseInRecordService;
    @Autowired
    private BaseCustomerService baseCustomerService;
    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private InService inService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProdPurchaseService prodPurchaseService;
    @Autowired
    private ProdPurchaseRecordService prodPurchaseRecordService;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private SysFileConfig sysFileConfig;

    /**
     * 查询采购订单列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<PurchaseInVO>> pagePurchaseIns(CommonPage<PurchaseInQueryParams, Page<PurchaseInVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();
        CommonPageBuilder<PurchaseInQueryDTO, ProdPurchaseIn> commonPageBuilder = new CommonPageBuilder<>(PurchaseInQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdPurchaseIn> page = prodPurchaseInService.page(commonPageBuilder.bulid(), loginUser);
        List<ProdPurchaseIn> orders = page.getRecords();
        //结果对象
        IPage<PurchaseInVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysPurchaseIn -> {
                PurchaseInVO orderVO = new PurchaseInVO();
                BeanUtil.copyProperties(sysPurchaseIn, orderVO);
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(sysPurchaseIn.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    baseCustomer = baseCustomerService.queryCustomerByCustomerCode(sysPurchaseIn.getCustomerCode(), loginUser);
                    baseCustomerMap.put(sysPurchaseIn.getCustomerCode(), baseCustomer);
                }
                orderVO.setCustomerName(baseCustomer.getCustomerName());
                //查询仓库信息
                WmsWarehouse wmsWarehouse = wmsWarehouseMap.get(sysPurchaseIn.getWarehouseCode());
                if (ObjectUtil.isEmpty(wmsWarehouse)) {
                    wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysPurchaseIn.getWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(wmsWarehouse.getWarehouseCode(), wmsWarehouse);
                }
                orderVO.setWarehouseName(wmsWarehouse.getWarehouseName());
                return orderVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }


    /**
     * 创建订单
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createOrder(PurchaseInCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询采购订单数据
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(createParams.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购订单不存在").checkCanIn("采购订单不能入库");
        PurchaseInBuilder orderBuilder = new PurchaseInBuilder();
        orderBuilder.append(createParams).append(prodPurchase).appendStatus(SaleStatusEnum.UN_CHECK.getValue()).appendCreate(loginUser);
        //总数
        final List<BigDecimal> quantity = new ArrayList<>();
        //金额统计
        final List<BigDecimal> total = new ArrayList<>();
        //卷数
        final List<Integer> juanTotal = new ArrayList<>();
        List<String> keys = new ArrayList<>();
        //保存商品信息
        List<ProdPurchaseInRecord> records = createParams.getGoods().stream().map(purchaseGoodsParams -> {
            if (keys.contains(purchaseGoodsParams.getKey())) {
                log.info("物料存在:{}", purchaseGoodsParams.getKey());
                throw BusinessExceptionFactory.newException("物料重复");
            }
            keys.add(purchaseGoodsParams.getKey());
            //查询商品是否存在
            ProdPurchaseRecord prodPurchaseRecord = prodPurchaseRecordService.queryRecord(purchaseGoodsParams, prodPurchase.getOrderNo(), loginUser);
            if (ObjectUtil.isNull(prodPurchaseRecord)) {
                log.info("商品{}不在订单中", JSON.toJSONString(purchaseGoodsParams));
                throw BusinessExceptionFactory.newException("入库商品不在采购订单中");
            }
            //采购退回订单数量
            quantity.add(purchaseGoodsParams.getQuantity());
            //计算单个商品总价
            total.add(purchaseGoodsParams.getQuantity().multiply(NumberUtil.null2Zero(prodPurchaseRecord.getPrice())));
            //卷数
            juanTotal.add(purchaseGoodsParams.getTotal());
            return new PurchaseInRecordBuilder().append(purchaseGoodsParams).appendOrderNo(prodPurchase.getOrderNo())
                    .appendRecordCode(prodPurchaseRecord.getCode()).appendCustomerCode(prodPurchase.getCustomerCode())
                    .appendPrice(prodPurchaseRecord.getPrice()).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());
        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(total.stream().reduce(BigDecimal::add).get());
        //保存卷数
        orderBuilder.appendJuanTotal(juanTotal.stream().mapToInt(Integer::intValue).sum());
        //保存订单信息
        if (!prodPurchaseInService.save(orderBuilder.bulid())) {
            log.info("保存订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("保存订单接口异常");
        }
        //更新采购订单完成数量
        UpdateQuantityDTO updateQuantityDTO = new UpdateQuantityDTO();
        updateQuantityDTO.setCode(prodPurchase.getOrderNo());
        updateQuantityDTO.setUpdateVersion(prodPurchase.getUpdateVersion());
        updateQuantityDTO.setTotal(prodPurchase.getTotal() + orderBuilder.getTotal());
        updateQuantityDTO.setQuantity(NumberUtil.null2Zero(prodPurchase.getFinishQuantity()).add(orderBuilder.getQuantity()));
        updateQuantityDTO.setAmount(NumberUtil.null2Zero(prodPurchase.getTotalAmount()).add(orderBuilder.getAmount()));
        if (!prodPurchaseService.updateFinishQuantity(updateQuantityDTO, loginUser)) {
            log.info("更新订单完成数量异常");
            throw BusinessExceptionFactory.newException("更新订单完成数量异常");
        }
        //保存数据
        prodPurchaseInRecordService.saveBatch(records);
        //保存文件
        sysFileService.saveFile(orderBuilder.getCode(), FileTypeEnum.PURCHASE_IN, FileRecordUtil.toFileDTO(createParams.getFiles()), loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 编辑订单
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editOrder(PurchaseInEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseIn prodPurchaseIn = prodPurchaseInService.queryPurchaseInByInCode(editParams.getInCode(), loginUser);
        new PurchaseInCheck(prodPurchaseIn).checkNull("采购入库单不存在").checkCanEdit("入库单不能编辑");
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(prodPurchaseIn.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购不存在").checkCanIn("采购订单不能入库");
        PurchaseInBuilder orderBuilder = new PurchaseInBuilder();
        orderBuilder.append(editParams).appendEdit(loginUser);
        //总数
        final List<BigDecimal> quantity = new ArrayList<>();
        //金额统计
        final List<BigDecimal> total = new ArrayList<>();
        //卷数
        final List<Integer> juanTotal = new ArrayList<>();
        List<String> keys = new ArrayList<>();
        //删除数据
        prodPurchaseInRecordService.deleteOrderGoods(editParams.getInCode(), loginUser);
        //保存商品信息
        List<ProdPurchaseInRecord> records = editParams.getGoods().stream().map(purchaseGoodsParams -> {
            if (keys.contains(purchaseGoodsParams.getKey())) {
                log.info("物料存在:{}", purchaseGoodsParams.getKey());
                throw BusinessExceptionFactory.newException("物料重复");
            }
            keys.add(purchaseGoodsParams.getKey());
            //查询商品是否存在
            ProdPurchaseRecord prodPurchaseRecord = prodPurchaseRecordService.queryRecord(purchaseGoodsParams, prodPurchase.getOrderNo(), loginUser);
            if (ObjectUtil.isNull(prodPurchaseRecord)) {
                log.info("商品{}不在订单中", JSON.toJSONString(purchaseGoodsParams));
                throw BusinessExceptionFactory.newException(SysMsgCodeConstant.Error.ERR10000022);
            }
            //采购退回订单数量
            quantity.add(purchaseGoodsParams.getQuantity());
            //计算单个商品总价
            total.add(purchaseGoodsParams.getQuantity().multiply(NumberUtil.null2Zero(prodPurchaseRecord.getPrice())));
            //保存卷数
            juanTotal.add(purchaseGoodsParams.getTotal());
            return new PurchaseInRecordBuilder().append(purchaseGoodsParams).appendOrderNo(prodPurchase.getOrderNo())
                    .appendRecordCode(prodPurchaseRecord.getCode()).appendCustomerCode(prodPurchase.getCustomerCode())
                    .appendPrice(prodPurchaseRecord.getPrice()).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());
        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(total.stream().reduce(BigDecimal::add).get());
        //保存卷数
        orderBuilder.appendJuanTotal(juanTotal.stream().mapToInt(Integer::intValue).sum());
        //编辑订单信息
        if (!prodPurchaseInService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //更新采购订单完成数量
        UpdateQuantityDTO updateQuantityDTO = new UpdateQuantityDTO();
        updateQuantityDTO.setCode(prodPurchase.getOrderNo());
        updateQuantityDTO.setUpdateVersion(prodPurchase.getUpdateVersion());
        updateQuantityDTO.setQuantity(NumberUtil.null2Zero(prodPurchase.getFinishQuantity()).add(orderBuilder.getQuantity())
                .subtract(prodPurchaseIn.getQuantity()));
        updateQuantityDTO.setAmount(NumberUtil.null2Zero(prodPurchase.getTotalAmount()).add(orderBuilder.getAmount())
                .subtract(prodPurchaseIn.getTotalAmount()));
        updateQuantityDTO.setTotal(prodPurchase.getTotal() + orderBuilder.getTotal() - prodPurchaseIn.getTotal());
        if (!prodPurchaseService.updateFinishQuantity(updateQuantityDTO, loginUser)) {
            log.info("更新订单完成数量异常");
            throw BusinessExceptionFactory.newException("更新订单完成数量异常");
        }
        //保存数据
        prodPurchaseInRecordService.saveBatch(records);
        //删除文件
        sysFileService.deleteFile(orderBuilder.getCode(), FileTypeEnum.PURCHASE_IN.getValue(), loginUser);
        //保存文件
        sysFileService.saveFile(orderBuilder.getCode(), FileTypeEnum.PURCHASE_IN, FileRecordUtil.toFileDTO(editParams.getFiles()), loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }


    /**
     * 审核通过
     *
     * @param inCode
     * @return
     */
    @Transactional
    public Result<String> passOrder(String inCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseIn prodPurchaseIn = prodPurchaseInService.queryPurchaseInByInCode(inCode, loginUser);
        new PurchaseInCheck(prodPurchaseIn).checkNull("采购入库不存在").checkCanCheck("采购入库单已经审核");
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(prodPurchaseIn.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购单不存在").checkCanIn("采购订单不能入库");
        PurchaseInBuilder orderBuilder = new PurchaseInBuilder();
        orderBuilder.appendCode(inCode).appendEdit(loginUser).appendStatus(PurchaseInStatusEnum.UN_IN.getValue());
        //编辑订单信息
        if (!prodPurchaseInService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("审核订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        OrderCreateDTO orderCreateDTO = new OrderCreateDTO();
        orderCreateDTO.setBusinessOrderNo(prodPurchase.getBusinessOrderNo());
        orderCreateDTO.setBusinessCode(inCode);
        orderCreateDTO.setWarehouseCode(prodPurchaseIn.getWarehouseCode());
        //查询订单商品
        List<ProdPurchaseInRecord> records = prodPurchaseInRecordService.list(inCode, loginUser);
        List<GoodsDTO> goodsDTOS = records.stream().map(prodPurchaseInRecord -> {
            return new GoodsBuilder().append(prodPurchaseInRecord).appendOrderNo(prodPurchase.getBusinessOrderNo()).bulid();
        }).collect(Collectors.toList());
        orderCreateDTO.setGoodsDTOS(goodsDTOS);
        //创建订单
        inService.createOrderIn(orderCreateDTO, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, inCode);
    }

    /**
     * 删除
     *
     * @param inCode
     * @return
     */
    @Transactional
    public Result<String> deleteOrder(String inCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseIn prodPurchaseIn = prodPurchaseInService.queryPurchaseInByInCode(inCode, loginUser);
        new PurchaseInCheck(prodPurchaseIn).checkNull("采购入库不存在").checkCanCheck("采购入库不能删除");
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(prodPurchaseIn.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购不存在");
        PurchaseInBuilder orderBuilder = new PurchaseInBuilder();
        orderBuilder.appendCode(inCode).appendEdit(loginUser).delete();
        //编辑订单信息
        if (!prodPurchaseInService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("删除订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("删除订单接口异常");
        }
        //删除数据
        prodPurchaseInRecordService.deleteOrderGoods(inCode, loginUser);
        //更新采购订单完成数量
        UpdateQuantityDTO updateQuantityDTO = new UpdateQuantityDTO();
        updateQuantityDTO.setCode(prodPurchase.getOrderNo());
        updateQuantityDTO.setUpdateVersion(prodPurchase.getUpdateVersion());
        updateQuantityDTO.setQuantity(NumberUtil.null2Zero(prodPurchase.getFinishQuantity())
                .subtract(prodPurchaseIn.getQuantity()));
        updateQuantityDTO.setAmount(NumberUtil.null2Zero(prodPurchase.getTotalAmount())
                .subtract(prodPurchaseIn.getTotalAmount()));
        updateQuantityDTO.setTotal(prodPurchase.getTotal() - prodPurchaseIn.getTotal());
        if (!prodPurchaseService.updateFinishQuantity(updateQuantityDTO, loginUser)) {
            log.info("更新订单完成数量异常");
            throw BusinessExceptionFactory.newException("更新订单完成数量异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, inCode);
    }


    /**
     * 取消
     *
     * @param inCode
     * @return
     */
    @Transactional
    public Result<String> cancelOrder(String inCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseIn prodPurchaseIn = prodPurchaseInService.queryPurchaseInByInCode(inCode, loginUser);
        new PurchaseInCheck(prodPurchaseIn).checkNull("采购入库单不存在").checkCanCancel("采购入库不能取消");
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(prodPurchaseIn.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购不存在");
        PurchaseInBuilder orderBuilder = new PurchaseInBuilder();
        orderBuilder.appendCode(inCode).appendStatus(PurchaseInStatusEnum.CANCEL.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodPurchaseInService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("取消订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("取消订单接口异常");
        }
        //作废出库订单
        inService.invalidOrderBusinessCode(inCode, loginUser);
        //更新采购订单完成数量
        UpdateQuantityDTO updateQuantityDTO = new UpdateQuantityDTO();
        updateQuantityDTO.setCode(prodPurchase.getOrderNo());
        updateQuantityDTO.setUpdateVersion(prodPurchase.getUpdateVersion());
        updateQuantityDTO.setQuantity(NumberUtil.null2Zero(prodPurchase.getFinishQuantity())
                .subtract(prodPurchaseIn.getQuantity()));
        updateQuantityDTO.setAmount(NumberUtil.null2Zero(prodPurchase.getTotalAmount())
                .subtract(prodPurchaseIn.getTotalAmount()));
        updateQuantityDTO.setTotal(prodPurchase.getTotal() - prodPurchaseIn.getTotal());
        if (!prodPurchaseService.updateFinishQuantity(updateQuantityDTO, loginUser)) {
            log.info("更新订单完成数量异常");
            throw BusinessExceptionFactory.newException("更新订单完成数量异常");
        }
        //取消入库明细
        prodPurchaseInRecordService.cancelOrderGoods(inCode, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, inCode);
    }


    /**
     * 订单详情
     *
     * @param inCode
     * @return
     */
    public Result<PurchaseInVO> viewOrder(String inCode) {
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseIn prodPurchaseIn = prodPurchaseInService.queryPurchaseInByInCode(inCode, loginUser);
        new PurchaseInCheck(prodPurchaseIn).checkNull("采购退货单不存在");
        PurchaseInVO purchaseVO = new PurchaseInVO();
        BeanUtil.copyProperties(prodPurchaseIn, purchaseVO);
        //查询客信息
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(prodPurchaseIn.getCustomerCode(), loginUser);
        if (ObjectUtil.isNotNull(baseCustomer)) {
            purchaseVO.setCustomerName(baseCustomer.getCustomerName());
        }
        //查询仓库信息
        WmsWarehouse wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(prodPurchaseIn.getWarehouseCode(), loginUser);
        if (ObjectUtil.isNotNull(wmsWarehouse)) {
            purchaseVO.setWarehouseName(wmsWarehouse.getWarehouseName());
        }
        //查询
        List<ProdPurchaseInRecord> prodPurchaseInRecords = prodPurchaseInRecordService.list(inCode, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();
        List<PurchaseGoodsVO> purchaseGoodsVOS = prodPurchaseInRecords.stream().map(prodPurchaseInRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodPurchaseInRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodPurchaseInRecord.getGoodsCode(), loginUser);
                modelMap.put(prodPurchaseInRecord.getGoodsCode(), materialModelVO);
            }
            return new PurchaseGoodsBuilder().append(prodPurchaseInRecord).append(materialModelVO).bulid();
        }).collect(Collectors.toList());
        purchaseVO.setGoods(purchaseGoodsVOS);
        //查询图片信息
        List<SysFile> files = sysFileService.queryFiles(inCode, FileTypeEnum.PURCHASE_IN.getValue(), loginUser);
        purchaseVO.setFiles(FileRecordUtil.toFileVO(files, sysFileConfig));
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, purchaseVO);
    }

    /**
     * 查询采购商品
     *
     * @param queryParams
     * @return
     */
    public Result<List<PurchaseGoodsVO>> listGoods(@Valid PurchaseInQueryParams queryParams) {
        LoginUser loginUser = LogInUserUtil.get();
        //查询生效的入库单
        List<ProdPurchaseIn> prodPurchaseIns = prodPurchaseInService.listFinishByOrderNos(Arrays.asList(queryParams.getOrderNo()), loginUser);
        List<String> inCodes = prodPurchaseIns.parallelStream().map(ProdPurchaseIn::getInCode).collect(Collectors.toList());
        List<ProdPurchaseInRecord> prodPurchaseInRecords = prodPurchaseInRecordService.listByOrderNo(queryParams.getOrderNo(), inCodes, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();
        List<PurchaseGoodsVO> goodsVOList = prodPurchaseInRecords.stream().map(prodPurchaseInRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodPurchaseInRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodPurchaseInRecord.getGoodsCode(), loginUser);
                modelMap.put(prodPurchaseInRecord.getGoodsCode(), materialModelVO);
            }
            return new PurchaseGoodsBuilder().append(prodPurchaseInRecord).append(materialModelVO).bulid();
        }).collect(Collectors.toList());
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, goodsVOList);
    }

    /**
     * 查询入库记录
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<PurchaseInRecordVO>> pagePurchaseInRecords(@Valid CommonPage<PurchaseInRecordQueryParams, Page<PurchaseInRecordVO>> queryParams) {

        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();
        Map<String, MaterialModelVO> modelMap = new HashMap<>();
        Map<String, ProdPurchase> purchaseMap = new HashMap<>();
        CommonPageBuilder<PurchaseInRecordQueryDTO, ProdPurchaseInRecord> commonPageBuilder = new CommonPageBuilder<>(PurchaseInRecordQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdPurchaseInRecord> page = prodPurchaseInRecordService.pageRecord(commonPageBuilder.bulid(), loginUser);
        List<ProdPurchaseInRecord> orders = page.getRecords();
        //结果对象
        IPage<PurchaseInRecordVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(prodPurchaseInRecord -> {
                MaterialModelVO materialModelVO = modelMap.get(prodPurchaseInRecord.getGoodsCode());
                if (ObjectUtil.isNull(materialModelVO)) {
                    materialModelVO = goodsService.queryGoodsByCode(prodPurchaseInRecord.getGoodsCode(), loginUser);
                    modelMap.put(prodPurchaseInRecord.getGoodsCode(), materialModelVO);
                }

                //查询采购单信息
                ProdPurchase prodPurchase = purchaseMap.get(prodPurchaseInRecord.getOrderNo());
                if (ObjectUtil.isNull(prodPurchase)) {
                    prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(prodPurchaseInRecord.getOrderNo(), loginUser);
                    purchaseMap.put(prodPurchaseInRecord.getOrderNo(), prodPurchase);
                }
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(prodPurchaseInRecord.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    if (StrUtil.isNotBlank(prodPurchaseInRecord.getCustomerCode())) {
                        baseCustomer = baseCustomerService.queryCustomerByCustomerCode(prodPurchaseInRecord.getCustomerCode(), loginUser);
                        baseCustomerMap.put(prodPurchaseInRecord.getCustomerCode(), baseCustomer);
                    }
                }
                PurchaseInRecordVO orderVO = new PurchaseInRecordVoBuilder().append(prodPurchaseInRecord)
                        .append(baseCustomer).append(materialModelVO).append(prodPurchase)
                        .appendTotalAmount(prodPurchaseInRecord.getQuantity().multiply(prodPurchaseInRecord.getPrice())).bulid();
                return orderVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }
}
